﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using System.Net;
using System.Net.Sockets;

using log4net;

using NetworkAssetManager;
using NetworkAssetManager.General; 

namespace NetworkAssetManager.Network
{
    class NetworkPing
    {
        private const int timeout = 2000;
        private string _IPorHostname = string.Empty;
        public NetworkPing()
        {
        }

        public NetworkPing(string IPorHostname)
        {
            _IPorHostname = IPorHostname; 
        }

        public string IPorHostname
        {
            set
            {
                _IPorHostname = value; 
            }
            get
            {
                return _IPorHostname; 
            }
        }

        public static bool Available(string IPorHostname)
        {
            bool bAvailable = false;
            Ping ping = new Ping();
            try
            {
                PingReply pingReply = ping.Send(IPorHostname, timeout);
                if (pingReply.Status == IPStatus.Success)
                {
                    bAvailable = true;
                }
            }
            catch (Exception)
            {
                bAvailable = false;
            }
            finally
            {
                if ( ping!=null)
                {
                    ping.Dispose();
                    ping = null;
                }
            }
            return bAvailable; 
        }

        public double AveragePingTime( int noOfPings)
        {
            double dAvg = 0;
            Ping ping = new Ping(); 

            for (int i = 0; i < noOfPings; i++)
            {
                PingReply pingReply = ping.Send(_IPorHostname, timeout);
                if ( pingReply.Status != IPStatus.Success)
                {
                    break; 
                }
                dAvg += pingReply.RoundtripTime; 

                //pingReply.Buffer.Count().ToString());
                //pingReply.RoundtripTime.ToString());
                //pingReply.Options.Ttl.ToString());
                //pingReply.Status.ToString());
                System.Threading.Thread.Sleep(100);
                if ( pingReply != null)
                {
                    pingReply = null;
                }
            }
            return dAvg / noOfPings; 
        }

    }
}
